package com.sx.service.utils;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.sx.entity.basic.FileEntity;
import com.sx.service.system.IConfigService;
import com.sx.utils.DateUtils;
import com.sx.utils.SnowflakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author AdinZ
 * @date 2020/11/11 17:07
 */
@Service
public class FileUploadService {

    private final UploadManager uploadManager;
    private JSONObject config;
    private Auth mAuth;

    public FileUploadService(IConfigService configService) {
        this.config=configService.findConfig("qiniu_file");
        this.mAuth=Auth.create(this.config.getString("accessKey"),this.config.getString("secretKey"));
        this.uploadManager = new UploadManager(new Configuration(Region.region2()));
    }

    public String upload(byte[] data,String path) throws QiniuException {
        Response response = this.uploadManager.put(data, path, mAuth.uploadToken(this.config.getString("bucket")));
        if (response == null) throw new RuntimeException("上传返回异常");
        if (!response.isOK()) throw new RuntimeException(response.bodyString());
        return this.config.getString("domain") + path;
    }

    public String upload(File file,String path) throws IOException {
        String domain = this.config.getString("domain");

        if(StringUtils.isEmpty(domain))throw new RuntimeException("还未设置文件域名");
        if(!StringUtils.startsWithAny(domain.toLowerCase(),"http://","https://")){
            throw new RuntimeException(domain+"域名设置有误");
        }
        Response response = this.uploadManager.put(file, path, mAuth.uploadToken(this.config.getString("bucket")));
        if (response == null) throw new RuntimeException("上传返回异常");
        if (!response.isOK()) throw new RuntimeException(response.bodyString());
        return this.config.getString("domain") + path;
    }



    public String upload(File file) throws IOException {
        if(file==null)throw new RuntimeException("文件为空");
        String filename = file.getName();
        String mime = "";
        try {
            mime = filename.substring(filename.lastIndexOf("."));
        } catch (Exception ex) {}
        String path=new StringBuffer(DateUtils.format("yyyy-MM-dd"))
                .append("/").append(SnowflakeIdWorker.generateId()).append(mime).toString();

        return this.upload(file,path);
    }

    public FileEntity upload(MultipartFile file) throws IOException {
        if(file==null)throw new RuntimeException("文件为空");
        String filename = file.getOriginalFilename();
        String mime = "";
        try {
            mime = filename.substring(filename.lastIndexOf("."));
        } catch (Exception ex) {}
        String path=new StringBuffer(DateUtils.format("yyyy-MM-dd"))
                .append("/").append(SnowflakeIdWorker.generateId()).append(mime).toString();
        String resPath= this.upload(file.getBytes(),path);
        FileEntity res=new FileEntity();
        res.setPath(resPath);
        res.setFormat(mime);
        res.setSize(file.getSize());
        return res;
    }




}
